package com.searchschool.persistence;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityTransaction;
import com.searchschool.bean.School;

public class SchoolImpl implements Serializable{


	private static final long serialVersionUID = 1L;
	private static SchoolImpl instance;
	private static EntityManager em;
	private static String pu = "Mi-JPA-con-JSF";
	private SchoolImpl(){
		setup();
	}
	
	
	private EntityManager setup() {
		if(em==null){
			EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);
			em=emf.createEntityManager();
		}
		return em;
	}
	
	public static SchoolImpl getInstance(){
		synchronized (SchoolImpl.class) {
            if (instance == null) 
                    instance = new SchoolImpl();
            return instance;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<School> findAll() {
	    String q = "SELECT x FROM SCHOOL x";
	    Query query = em.createQuery(q);
	    return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<School> sortByField(String sortfield, boolean asc) {
	    String q = "SELECT e FROM SCHOOL e ORDER BY e." + sortfield + " ";
	    if(asc) {
	       q += "ASC";
	     } else {
	       q += "DESC";
	    }
	    Query query = em.createQuery(q);
	    return query.getResultList();
	}
	
	public void insert(School school) {
		EntityTransaction t = em.getTransaction();
		try {
			t.begin();
			em.persist(school);
			t.commit();
		} finally {
			if ( t.isActive() ) {
				t.rollback();
			}
			em.close();
		}
	}
	
	public void update(School school) {
		em.getTransaction().begin();
		em.merge(school);
		em.flush();
		em.getTransaction().commit();		
	}
	
	public void delete(School school) {
		em.getTransaction().begin();
		em.remove(school);
		em.flush();
		em.getTransaction().commit();
	}

}
